/*	Copyright 2008 Jacquemin Valentin

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
	
	@author pollux
 */
package org.poxd.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeSelectionModel;

import org.poxd.model.CategoriesModel;
import org.poxd.model.Category;
import org.poxd.model.Language;
import org.poxd.model.Snippet;

/**
 * @author pollux
 * 
 */
public class CategoriesPanel extends JPanel {
	private static final long serialVersionUID = 1L;
	private final JTree categories;
	private Language selectedLanguage;
	private final CategoriesModel model;
	private MainPane mainController;
	private Category currentCategory;
	private final TreeSelectionListener selectionListner = new SnippetSelection();

	public CategoriesPanel(MainPane controller) {
		mainController = controller;
		setBackground(Color.WHITE);
		model = new CategoriesModel();
		categories = new JTree(model);
		categories.addKeyListener(new DeleteKeyListener());
		categories.addMouseListener(new DoubleClicListener());
		categories.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
		categories.getSelectionModel().setSelectionMode(
				TreeSelectionModel.SINGLE_TREE_SELECTION);
		categories.addTreeSelectionListener(selectionListner);
		categories.setEditable(false);
		categories.setRootVisible(false);
		setLayout(new BorderLayout());
		setMinimumSize(new Dimension(180, getMinimumSize().height));
		add(categories);
	}

	public void addSnippet(Snippet snip) {
		if (currentCategory.getSnippets().contains(snip)) {
			Snippet s = currentCategory.getSnippets().get(
					currentCategory.getSnippets().indexOf(snip));
			s.setCode(snip.getCode());
			s.setDescription(snip.getDescription());
			s.setTitle(snip.getTitle());
		} else {
			currentCategory.getSnippets().add(snip);
		}
	}

	public void setSelectedLanguage(final Language selectedLanguage) {
		this.selectedLanguage = selectedLanguage;
		Map<String, Category> categories = this.selectedLanguage
				.getCategories();
		model.setCategories(categories);
		currentCategory = model.getFirstCategory();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				CategoriesPanel.this.repaint();
			}
		});
	}

	public Category getCurrentCategory() {
		return currentCategory;
	}

	public Category getNewCategory(String string) {
		return new Category(string, new ArrayList<Snippet>());
	}

	private class SnippetSelection implements TreeSelectionListener {
		public void valueChanged(TreeSelectionEvent e) {
			// HACK
			if (!e.isAddedPath()) {
				return;
			}
			mainController.setSnippet(null);
			Object selection = e.getPath().getLastPathComponent();
			if (selection instanceof Snippet) {
				Snippet snip = (Snippet) selection;
				mainController.setSnippet(snip);
				Category snipCategory = model.getSnippetCategory(snip);
				if (currentCategory != snipCategory) {
					currentCategory = snipCategory;
				}
			} else {
				currentCategory = (Category) selection;
			}
		}
	}

	private class DeleteKeyListener extends KeyAdapter {
		public void keyTyped(KeyEvent e) {
			if (e.getKeyChar() != KeyEvent.VK_DELETE)
				return;
			final JTree source = (JTree) e.getSource();
			new Thread(new Runnable() {
				public void run() {
					Object selected = source.getLastSelectedPathComponent();
					if (selected instanceof Category) {
						// CategoriesDAO dao = new CategoriesDAO();
						// dao.deleteCategory((Category) selected);
						mainController.removeCategory((Category) selected);
					} else if (selected instanceof Snippet) {
						// SnippetDAO dao = new SnippetDAO();
						// dao.deleteSnippet((Snippet) selected);
						currentCategory.getSnippets()
								.remove((Snippet) selected);
					}
					setSelectedLanguage(selectedLanguage);
				}
			}, "DELETE CATEGORY THREAD").start();
		}
	}

	private class DoubleClicListener extends MouseAdapter {
		@Override
		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() == 2) {
				e.consume();
				if (((JTree) e.getSource()).getLastSelectedPathComponent() instanceof Snippet) {
					mainController
							.editSnippet((Snippet) ((JTree) e.getSource())
									.getLastSelectedPathComponent());
				}
			}
		}
	}

}
